/**
 * Created by 1 on 2016/12/30.
 */
(function () {
    "use strict";
    function Board(gameInst) {
        this.gameInst = gameInst;
        this.blockSize = 30;
        this.rows = window.TetrisConfig.rows;
        this.cols = window.TetrisConfig.cols;
        this.canvas = new Canvas("game_main", this.cols * this.blockSize, this.rows * this.blockSize);
        this.score = new window.Score();
        this.level = new window.Level();
        this.highScore = new window.HighScore();
        this.context = this.canvas.context;
        this.boardlist = [];//边界控制
        this.shape = new window.Shape();
        this._init();
    }

    Board.prototype = {
        _init: function () {
            this._buildGridData();
            this._initGrid();
            this.shape.draw(this.context);
            this._buildShape();
        },
        _buildGridData: function () {
            for (var i = 0; i < this.rows; i++) {
                this.boardlist[i] = [];
                for (var j = 0; j < this.cols; j++) {
                    this.boardlist[i][j] = 0;
                }
            }
        },
        //绘制画布
        _initGrid: function () {
            this.context.strokeStyle = "green";
            this.context.lineWidth = 0.5;
            this.context.beginPath();
            //绘制线条的笔迹
            for (var i = 0; i <= this.rows; i++) {
                this.context.moveTo(0, i * this.blockSize);
                this.context.lineTo(this.canvas.width, i * this.blockSize)
            }
            for (var i = 0; i <= this.cols; i++) {
                this.context.moveTo(i * this.blockSize, 0);
                this.context.lineTo(i * this.blockSize, this.canvas.height);
            }
            //调用绘制方法绘制
            this.context.stroke();
            //缓存数据
            this.gridImageData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
        },
        //下一步方块定位
        _buildShape: function () {
            this.nextShape = new window.Shape();
            this.nextShape.setPosition(this.gameInst.nextShape.cols, this.gameInst.nextShape.rows);
            this.gameInst.nextShape._render(this.nextShape);
        },
        tick: function () {
            if (this.validMove(0, 1)) {
                this.shape.y++;
            } else {
                this.addShapeTOBoardList();
                this.shape = this.nextShape;
                this.shape.x = 0;
                this.shape.y = 0;
                this._buildShape();
            }
            this.refresh();
            this.clearFullRows();
            if (this.gameInst._state !== "over") {
                this.shape.draw(this.context);
            } else {
                window.alert("Game Over!");
            }
        },
        //刷新画布
        refresh: function () {
            this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
            this.context.putImageData(this.gridImageData, 0, 0);
            this.drawBlocks();
        },
        //检查越界算法
        validMove: function (moveX, moveY) {
            this.nextX = this.shape.x + moveX;
            this.nextY = this.shape.y + moveY;
            for (var i = 0; i < this.shape.layout.length; i++) {
                for (var j = 0; j < this.shape.layout[i].length; j++) {
                    if (this.shape.layout[i][j]) {
                        if (typeof this.boardlist[this.nextY + j] === 'undefined' //找不到行
                            || typeof this.boardlist[this.nextY + j][this.nextX + i] === 'undefined' //找不到列
                            || this.boardlist[this.nextY + j][this.nextX + i] //当前位置已有方块
                            || this.nextX + i < 0 //超出左边界
                            || this.nextX + i >= this.cols // 超出右边界
                            || this.nextY + j >= this.rows // 超出下边界
                        ) {
                            return false;
                        }
                    }
                }
            }
            return true;
        },
        //方块堆砌
        addShapeTOBoardList: function () {
            for (var i = 0; i < this.shape.layout.length; i++) {
                for (var j = 0; j < this.shape.layout[i].length; j++) {
                    if (this.shape.layout[i][j]) {
                        this.boardX = this.shape.x + i;
                        this.boardY = this.shape.y + j;
                        for (var x = 0; x < window.TetrisConfig.cols; x++) {
                            if (this.boardlist[0][x]) {
                                this.gameInst._state = "over";
                                this.gameInst.endGame();
                            } else {
                                this.boardlist[this.boardY][this.boardX] = this.shape.blockType;
                            }

                        }
                    }
                }
            }
        },
        drawBlocks: function () {
            for (var y = 0; y < this.rows; y++) {
                for (var x = 0; x < this.cols; x++) {
                    if (this.boardlist[y][x]) {
                        this.shape.block.draw(this.context, x, y, this.boardlist[y][x]);
                    }
                }
            }
        },
        //增加行
        createEmptyRow: function () {
            var emptyArr = [];
            for (var i = 0; i < this.cols; i++) {
                emptyArr.push(0);
            }
            return emptyArr;
        },
        //方块消除
        clearFullRows: function () {
            var lines = 0;
            for (var y = this.rows - 1; y >= 0; y--) {
                this.filled = this.boardlist[y].filter(function (item) {
                        return item > 0;
                    }).length === this.cols;
                if (this.filled && y >= 0) {
                    this.boardlist.splice(y, 1);
                    this.boardlist.unshift(this.createEmptyRow());
                    y++;
                    lines++;
                }
            }
            var score = lines * 100 * lines;
            var totalScore = this.score.addScore(score);
            this.highScore.checkScore(totalScore);
            var currentLevel = this.level.checkLevel(totalScore);
            if (currentLevel) {
                window.TetrisConfig.speed = Math.floor(window.TetrisConfig.constSpeed * (1 - (currentLevel - 1) / 10));
                window.setTimeout(function () {
                    window.alert("恭喜升级！");
                })
            }
        }
    };
    window.Board = Board;
})();